<?php
declare(strict_types=1);

namespace Service\OrderService;

use App\Model\BbcModel\Order;
use App\Model\BbcModel\OrderReturn;
use Service\BaseService;
use Service\Code\Normal;
use App\Model\BbcModel\OrderReportStatus;
use Service\HelperService\StringService;
use Service\HelperService\DateService;
use Service\ChannelService\StoreConfigService;
use Hyperf\DbConnection\Db;

class ScreenOrderService extends BaseService
{
    public $clear_status = [
        0 => '申报中',
        1 => '清关成功',
        2 => '清关失败',
    ];

    public $express_status = [
        0 => '申报中',
        1 => '申报成功',
        2 => '申报失败',
    ];
    public function screenReportOrderData($param) {
        $page=$param['page']??1;
        $limit=$param['limit']??10;
        $start=($page-1)*$limit;
        $mn_sid=$param['mn_sid'];        
        $time= strtotime(date('Y-m-d'));
        $screendata_config=StoreConfigService::instance()->getConfig('screendata_config', (int)$mn_sid);
        $select=[
            'ors.*',
            'o.buyer_name',
            'o.buyer_mobile',
            'o.sn',
            'o.pay_time',
            'o.cd',
            'o.status',
            'oe.serial_number'
        ];
        $table = OrderReportStatus::instance()->getTable();
        $query = OrderReportStatus::instance()
            ->from("{$table} as ors")
            ->join('ly_order as o','ors.order_id','=','o.id')
            ->join('ly_order_extends as oe','ors.order_id','=','oe.order_id')
            ->select($select);
        $query->where('o.status','>=',20)
            ->where('o.type','=',4)
            ->where('ors.mn_sid',$mn_sid);
        if(isset($param['refresh_time'])&& $param['refresh_time']>0){
            $query->where('ors.md','>=',$param['refresh_time']);
        } 
        if(!empty($screendata_config)&&$screendata_config['show_type']==1){
            //全部数据模式
        }else{
            //当天数据，（show_type==0或者默认也是）
            $query->where('o.cd','>=',$time);
        }
        $query->orderBy('ors.md','desc');
        $totalcount=$query->count();
//        $query->offset($start);
//        $query->limit($limit);
        $list  =  $query->get()->toArray();
        $data=[];
        $time=time();
        foreach ($list as $value) { 
            $package_status='-';
            if($value['delivery_status']==2){
                $package_status='打包中';
            }
            $fivetime=$value['delivery_time']+300;
            if($value['delivery_status']==2 &&$time>=$fivetime){
                $package_status='已投递';
            }
            $data[]=[
                'order_id'=>$value['order_id'],
                'sn'=>'*'.substr($value['sn'],-4),
                'buyer_name'=> StringService::make_star($value['buyer_name']), 
                //'buyer_mobile'=>str_replace(substr($value['buyer_mobile'], 3, 4), '****', $value['buyer_mobile']),
                'buyer_mobile'=>'*'.substr($value['buyer_mobile'],-4),
                'pay_time'=> date('H:i:s',$value['pay_time']),
                'clear_time'=>$value['clear_status']==0?'':date('H:i:s',$value['clear_time']),
                'time'=> $value['clear_status']==0?'':DateService::timesecond($value['cd'], $value['clear_time']),
                'status'=> $this->clear_status[$value['clear_status']],
                'package_status'=>$package_status,
                'serial_number'=>'H-'.str_pad((string)$value['serial_number'], 4, '0', STR_PAD_LEFT),
            ];
        }
        return Normal::returnCode(Normal::SUC, '成功', ['list'=>$data,'totalcount'=>$totalcount]);
    }

    public function screenOrderList($param)
    {
        $mn_sid            = $param['mn_sid'] ?? 0;
        $seven_days_ago    = strtotime("-120 days", time());
        $clear_status      = $param['clear_status'] ?? 0;
        $select = [
            '*',
        ];
        $query = Order::instance()
            ->where('mn_sid', $mn_sid)
            ->whereIn('type',[0,1,2])
            ->where('status','>=',20)
            ->where('cd','>=',$seven_days_ago);
        if($clear_status == 0) //清关中,就是已下单支付未发货
        {
            $query->where('status','=',20);
        }
        else //清关完成，就是已发货
        {
            $query->where('status','>=',30);
        }
        $query->orderBy('md','desc');
        $list = $query->get()->toArray();

        $returnData = [];

        $totalcount = $query->count();
        foreach ($list as $value)
        {
            $strlen     = mb_strlen($value['buyer_name'], 'utf-8');
            $firstStr   = mb_substr($value['buyer_name'], 0, 1, 'utf-8');
            $lastStr    = mb_substr($value['buyer_name'], -1, 1, 'utf-8');
            $buyer_name = $strlen == 2 ? $firstStr . str_repeat('*', mb_strlen($value['buyer_name'], 'utf-8') - 1) : $firstStr . str_repeat("*", $strlen - 2) . $lastStr;


            $returnData[] = [
                'sn'           => '****' . substr($value['sn'], -4),
                'buyer_name'   => $buyer_name,
                'buyer_mobile' => '****' . substr($value['buyer_mobile'], -4),
                'pay_time'     => date('H:i:s', $value['pay_time']),

            ];
        }
        return Normal::returnCode(Normal::SUC, '成功', ['list'=>$returnData,'totalcount'=>$totalcount]);
    }
}
